package org.tiger.netty.server.nio;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lwl
 * @date 2020/10/9 9:39 下午
 */
public class SelectorTest {

	private static Logger logger = LoggerFactory.getLogger(SelectorTest.class);

	public static void main(String[] args) throws Exception {
		int[] ports = new int[5];
		ports[0] = 15003;
		ports[1] = 15004;
		ports[2] = 15005;
		ports[3] = 15006;
		ports[4] = 15007;

		Selector selector = Selector.open();

		for (int port : ports){
			ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.configureBlocking(false);
			ServerSocket serverSocket = serverSocketChannel.socket();
			InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
			serverSocketChannel.bind(inetSocketAddress);
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
			logger.info("监听端口:" + port);
		}

		while (true){

			int numbers = selector.select();
			logger.info("numbers:" + numbers);
			Set<SelectionKey> selectionKeys = selector.selectedKeys();
			logger.info("selectionKeys:" + selectionKeys);
			Iterator<SelectionKey> iterable = selectionKeys.iterator();

			while (iterable.hasNext()){
				SelectionKey selectionKey = iterable.next();

				if (selectionKey.isAcceptable()){
					ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey
							.channel();
					SocketChannel socketChannel = serverSocketChannel.accept();
					socketChannel.configureBlocking(false);
					socketChannel.register(selector, SelectionKey.OP_READ);
					iterable.remove();
					logger.info("获取到客户端连接：" + socketChannel);
				} else if (selectionKey.isReadable()){
					SocketChannel socketChannel = (SocketChannel) selectionKey
							.channel();
					int byteRead = 0;
					while (true){
						ByteBuffer byteBuffer = ByteBuffer.allocate(512);
						int read = socketChannel.read(byteBuffer);
						if (read <= 0){
							break;
						}
						byteBuffer.flip();
						socketChannel.write(byteBuffer);
						byteRead += read;
					}
					logger.info("读取：" + byteRead + "，来自：" + socketChannel);
					iterable.remove();
				}

			}

		}

	}

}
